<?php

/*
 * Inviqa\Kmp
 *
 * Copyright © 2016 Inviqa Ltd
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * PHP version 7.0+
 */

declare(strict_types = 1);

namespace Kmp;

use SplFixedArray;

/**
 * Searches for the occurrence of a needle within a haystack.
 *
 * @param string $needle   The needle to search for within the haystack.
 * @param string $haystack The haystack in which the needle should be found.
 *
 * @return int
 *  The zero-based position at which the needle is found in the haystack.
 *  If the needle is not found within the haystack, -1 is returned.
 */
function search(string $needle, string $haystack): int
{
    if (!$needleLength = mb_strlen($needle)) {
        return -1;
    }

    $lps = new SplFixedArray($needleLength);
    $lps[0] = 0;

    for ($i = 1; $i < $needleLength; $i++) {
        $j = $lps[$i - 1];
        $cnc = $needle{$i};

        while ($j > 0 && $cnc !== $needle{$j}) {
            $j = $lps[$j - 1];
        }

        if ($cnc === $needle{$j}) {
            $j++;
        }

        $lps[$i] = $j;
    }

    $haystack = preg_split('//u', $haystack, -1, PREG_SPLIT_NO_EMPTY);
    $needle = preg_split('//u', $needle, -1, PREG_SPLIT_NO_EMPTY);
    $haystackLength = count($haystack);

    $matches = 0;
    for ($i = 0; $i < $haystackLength; $i++) {
        $chc = $haystack[$i];
        $cnc = $needle[$matches];

        while ($matches > 0 && $chc !== $cnc) {
            $matches = $lps[$matches - 1];
        }

        if ($chc === $cnc) {
            $matches++;

            if ($needleLength === $matches) {
                return $i - ($matches - 1);
            }
        }
    }

    return -1;
}
